import {
  saveRwghmxApi,
  getRwghmxPageApi,
  deleteRwghmxApi,
  updateRwghmxApi
} from './api/index'
import { uploadJcmcFileApi } from '../decisionModel/api'
import { modelBuildMethodOption } from '@/assets/data/pathInfo'

export default {
  components: {},
  data() {
    return {
      formInline: {
        demand: '',
        targetArea: '',
        sample: ''
      },
      labelPosition: 'right',
      formLabelAlign: {
        fileInfo: {
          fileName: '',
          filePath: ''
        }
      },
      tableData: [],
      dialogVisible: false,
      pageCurrent: 1,
      pageSize: 10,
      total: 0,
      multipleSelection: [],
      mxCommit: false,
      rules: {
        mxmc: [{ required: true, message: '请输入模型名称', trigger: 'blur' }],
        // jbsf: [{ required: true, message: '请输入基本算法', trigger: 'blur' }],
        sfmc: [{ required: true, message: '请输入算法名称', trigger: 'blur' }],
        // yrwsl: [
        //   { required: true, message: '请输入元任务数量', trigger: 'blur' }
        // ],
        rwfgl: [
          { required: false, message: '请输入任务完成率', trigger: 'blur' }
        ],
        mxlx: [{ required: true, message: '请输入模型类型', trigger: 'blur' }],
        mxgjfs: [
          { required: true, message: '请选择模型构建方式', trigger: 'change' }
        ],
        bbxx: [
          { required: true, message: '请输入模型版本信息', trigger: 'blur' }
        ]
      },
      dialogTitle: '添加模型',
      isFileUploaded: false,
      modelBuildMethodOption
    }
  },
  computed: {},
  created() { },
  mounted() {
    this.getRwghmxPageData(this.formInline)
  },
  methods: {
    // 导出任务规划模型
    exportRwghmxZip() {
      if (this.multipleSelection.length === 0) {
        return this.$message.warning('请选择要导出的数据')
      }
      if (this.multipleSelection.length > 1) {
        return this.$message.warning('每次只可以导出一条数据')
      }

      this.$message.warning('正在导出')

      const rowValue = this.multipleSelection[0]

      try {
        window.open(
          window.ipConfig.api +
          '/ybgl/jcmx/downloadZip?mxId=' +
          rowValue.mxid +
          '&mxType=RWGHMX'
        )
      } catch (error) {
        console.error('下载Excel失败:', error)
        this.$message.error('导出失败')
      }
    },
    // 跳转到训练页面
    startTrain(row) {
      sessionStorage.setItem('missionInfo', JSON.stringify(row))
      this.$router.push({
        path: '/model-management/mission-planning/train',
        query: {
          id: row.mxid
        }
      })
    },

    initFromLabel() {
      this.formLabelAlign = {
        fileInfo: {
          fileName: '',
          filePath: ''
        }
      }
    },
    deleteRwghmxData() {
      if (this.multipleSelection.length === 0) {
        this.$message.warning('请选择需要删除的数据!')
        return
      }
      const idList = []
      this.multipleSelection.forEach(item => {
        idList.push(item.mxid)
      })
      const data = {
        ids: idList
      }
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteRwghmxApi(data).then(res => {
          if (res.data.code === 200) {
            this.$message.success('操作成功')
            this.getRwghmxPageData(this.formInline)
          } else {
            this.$message.error('操作失败')
          }
        })
      })
    },
    // 编辑
    sampleEdit(row) {
      Object.keys(row).forEach(key => {
        this.$set(this.formLabelAlign, key, row[key])
      })
      this.dialogTitle = '编辑模型'
      this.dialogVisible = true
      this.mxCommit = false
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    // 添加模型
    addModelAndAssess() {
      this.initFromLabel()
      this.dialogTitle = '添加模型'
      this.dialogVisible = true
    },
    // 选择文件上传
    async selectWjButton() {
      let that = this
      // 点击后禁用上传按钮
      // that.isFileUploaded = true
      function callbackFn(event) {
        if (event.target.files.length > 0) {
          // 确保只执行一次上传
          that.mxCommit = true
          const file = event.target.files[0]
          that.formLabelAlign.fileInfo.fileName = file.name

          const formData = new FormData()
          formData.append('file', file)

          uploadJcmcFileApi(formData)
            .then(res => {
              if (res.data.code === 200) {
                that.formLabelAlign.fileInfo.filePath = res.data.message
                that.$message.success('操作成功')
                // that.isFileUploaded = false // 更新状态
                that.mxCommit = false
                // 移除事件监听，防止重复触发
                changeFile.removeEventListener('change', callbackFn, false)
              } else {
                that.$message.error('操作失败')
              }
            })
            .catch(error => {
              console.error('上传文件时发生错误:', error)
              that.$message.error('上传文件失败')
            })
        }
      }
      // 触发文件选择
      const changeFile = document.getElementById('fileUpload')
      changeFile.removeEventListener('change', callbackFn, false)
      changeFile.click()
      // 监听文件选择变化
      changeFile.addEventListener('change', callbackFn, false)
    },
    saveAndUpdateRwghData() {
      this.$refs.rwghFrom.validate(valid => {
        if (valid) {
          if (this.formLabelAlign.mxid && this.formLabelAlign.mxid !== '') {
            this.updateRwghmxData()
          } else {
            this.saveRwghmxData()
          }
        }
      })
      // 清空之前上传的文件
      document.getElementById('fileForm').reset()
    },
    // 保存任务规划模型
    saveRwghmxData() {
      saveRwghmxApi(this.formLabelAlign).then(res => {
        if (res.data.code === 200) {
          this.$message.success('操作成功')
          this.getRwghmxPageData(this.formInline)
          this.dialogVisible = false
          this.mxCommit = true
          this.initFromLabel()
        } else {
          this.$message.error('操作失败')
        }
      })
    },
    // 更新任务规划模型数据
    updateRwghmxData() {
      updateRwghmxApi(this.formLabelAlign).then(res => {
        if (res.data.code === 200) {
          this.$message.success('操作成功')
          this.dialogVisible = false
          this.mxCommit = true
          this.pageCurrent = 1
          this.getRwghmxPageData(this.formInline)
        } else {
          this.$message.error('操作失败')
        }
      })
    },
    // 任务规划模型分页
    getRwghmxPageData(data) {
      const query = {
        ...data,
        pageCurrent: this.pageCurrent,
        pageSize: this.pageSize
      }
      getRwghmxPageApi(query).then(res => {
        if (res.data.code === 200) {
          const data = res.data
          this.tableData = data.data.records
          this.total = data.data.total
        }
      })
    },
    cancelRwghDialog() {
      // 清空之前上传的文件
      this.$refs.rwghFrom.resetFields()
      document.getElementById('fileForm').reset()
      this.initFromLabel()
      this.dialogVisible = false
    },
    onSubmit() {
      this.pageCurrent = 1
      this.getRwghmxPageData(this.formInline)
    },
    // 重置按钮
    cleanSubmit() {
      this.pageCurrent = 1
      this.formInline = {}
      this.getRwghmxPageData(this.formInline)
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
    }
  }
}
